package com.cheng.reggie.service.impl;

import com.cheng.reggie.dto.DishDto;
import com.cheng.reggie.entity.Category;
import com.cheng.reggie.entity.Dish;
import com.cheng.reggie.entity.DishFlavor;
import com.cheng.reggie.entity.Page;
import com.cheng.reggie.exception.BusinessException;
import com.cheng.reggie.mapper.*;
import com.cheng.reggie.service.DishService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DishServiceImpl implements DishService {

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private DishFlavorMapper dishFlavorMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;






    /**
     * 根据分类id去查询菜品列表方法
     *
     * @param categoryId
     * @return List
     */
    @Autowired(required = false)
    RedisTemplate redisTemplate;

    @Override
    public List<DishDto> findByCategoryId(Long categoryId,Integer status) {
        //从缓存获取数据,缓存的key="dish_"+categoryId+"_"+status
        String key = "dish_"+categoryId+"_"+status;
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //调用mapepr根据类别id和状态查询菜品列表
        if(dishDtoList == null){
            List<Dish> dishList = dishMapper.findByCategoryIdAndStatus(categoryId, status);
            //2.加工处理dishList封装到List<DishDto>,完善里面口味列表数据
             dishDtoList = dishList.stream().map((dish -> {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish,dishDto);
                //根据菜品id获取口味列表数据封装到DishDto里面去
                List<DishFlavor> dishFlavorList = dishFlavorMapper.findByDishId(dishDto.getId());
                dishDto.setFlavors(dishFlavorList);
                return dishDto;
            })).collect(Collectors.toList());

            //将数据库查到数据写入缓存
            redisTemplate.opsForValue().set(key,dishDtoList);
        }

        return dishDtoList;
    }


    /**
     * 通过id修改菜品
     * @param dishDto
     * @return boolean
     */
    @Override
    @Transactional
    public boolean updateById(DishDto dishDto) {
        //完善数据
        //修改时间
        dishDto.setUpdateTime(LocalDateTime.now());
        //2 修改菜品
        dishMapper.updateById(dishDto);

        //删除该菜品的所有口味信息
        dishFlavorMapper.deleteByDishId(dishDto.getId());

        List<DishFlavor> flavors = dishDto.getFlavors();

        List<DishFlavor> dishFlavorList = flavors.stream().map((dishFlavor ->{
            //dishFlavor获取集合中每个元素
            // 获取菜品主键,设置修改人,创建人,修改时间,创建时间,
                dishFlavor.setDishId(dishDto.getId());
                dishFlavor.setName(dishDto.getName());
                dishFlavor.setUpdateTime(LocalDateTime.now());
                dishFlavor.setCreateTime(LocalDateTime.now());
                dishFlavor.setCreateUser(dishDto.getCreateUser());
                dishFlavor.setUpdateUser(dishDto.getUpdateUser());
                //批量保存口味数据
                return dishFlavor;
        })).collect(Collectors.toList());


         dishFlavorMapper.sava(dishFlavorList);
         redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return true;
    }

    /**
     *  通过id查询一个菜品和多个口味
     *
     * @param id
     * @return DishDto
     */
    @Override
    public DishDto findById(Long id) {
        return dishMapper.findById(id);
    }

    /**
     * 分页查询(多表查询)
     *
     * @param page
     * @param pageSize
     * @param name
     * @return Page
     */
    @Override
    public Page<DishDto> findByPage2(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);
        List<DishDto> dishDtoList = dishMapper.findAll2(name);
        PageInfo<DishDto> pageInfo = new PageInfo<>(dishDtoList);
        Page<DishDto> pageObj = new Page<>();
        pageObj.setRecords(dishDtoList);
        pageObj.setTotal(pageInfo.getTotal());

        return pageObj;
    }




    /**
     * 分页查询(分表查询)
     *
     * @param page
     * @param pageSize
     * @param name
     * @return Page
     */
    @Override
    public Page<DishDto> findByPage1(Integer page, Integer pageSize, String name) {
        //设置分页查询第几页和每页多少条
        PageHelper.startPage(page,pageSize);
        List<Dish> dishList = dishMapper.findAll(name);
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);

        //对dishList中每个dish菜品对象进行循环
        List<DishDto> dishDtoList = dishList.stream().map((dish -> {
            DishDto dishDto = new DishDto();

            //一个DishDto包含的一个Dish
            //将dish中里面的所有数据赋值给dishDto对象里面去
            BeanUtils.copyProperties(dish,dishDto);
            //根据分类id查询分类对象
            Category category = categoryMapper.findById(dishDto.getCategoryId());
            //将分类对象中分类名称赋值给dishDto对象中
            dishDto.setCategoryName(category.getName());
            return dishDto;
        })).collect(Collectors.toList());

        Page<DishDto> pageObj = new Page<>();
        pageObj.setRecords(dishDtoList);
        pageObj.setTotal(pageInfo.getTotal());

        return pageObj;
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return boolean
     */
    @Transactional  //开始事务注解扫描
    @Override
    public boolean save(DishDto dishDto) {
        //1.完善数据
        //(添加时间,修改时间,sort默认为0,是否禁售设置1起售)
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setSort(0);
        dishDto.setStatus(1);

        //2.调用数据访问层的添加菜品,要求获取菜品添加后菜品主键id
        dishMapper.insert(dishDto);

        List<DishFlavor> dishFlavorList =  dishDto.getFlavors().stream().map((dishFlavor -> {
            //dishFlavor 是获取集合中的每个元素对象
            //(设置菜品的主键,更新时间,创建时间,更新人,修改人)
            dishFlavor.setDishId(dishDto.getId());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(dishDto.getCreateUser());
            dishFlavor.setUpdateUser(dishDto.getUpdateUser());
            return dishFlavor;
        })).collect(Collectors.toList());
        //4.调用数据访问层插入多条口味的记录数据
        dishFlavorMapper.sava(dishFlavorList);

        //清除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return true;
    }
}
